package com.example.test2018131664.controller;

import com.example.test2018131664.bean.UserTable;
import com.example.test2018131664.service.UserService;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.support.SessionStatus;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class IndexController {

    @Resource
    UserService userService;

    //  登陆
    @RequestMapping(value = "/loginIn",method = RequestMethod.POST)
    public String login(String name, String password,HttpSession session){
        UserTable userTable = userService.loginIn(name,password);
        if(userTable!=null){
            session.setAttribute("user",userTable);
            return "success";
        }else{
            return "error";
        }
    }

    //    注册
    @RequestMapping("/addUser")
    @ResponseBody
    public Map addUser(UserTable userTable){
        int flag = userService.insertUser(userTable);
        Map<String,Object> map = new HashMap<String, Object>();
        if(flag == 1){
            map.put("msg","注册成功 ！");
            return map;
        }else{
            map.put("msg","注册失败 ！");
            return map;
        }
    }

    //    显示
//    @RequestMapping("/user")
//    public String showUser(ModelMap modelMap){
//        List<UserTable> userList = userService.getAllUser();
//        modelMap.addAttribute("userList",userList);
//        return "user";
//    }
    @RequestMapping("/user")
    public String index(Model model, @RequestParam(defaultValue = "2") Integer pageNum, @RequestParam(defaultValue = "3") Integer pageSize) {
        PageInfo<UserTable> pageInfo = userService.selectUser4Page(pageNum, pageSize);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("userList", pageInfo.getList());
        return "user";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session, SessionStatus sessionStatus){
        session.invalidate();
        sessionStatus.setComplete();
        return "redirect:/";
    }

}
